package utils;

import service.Node;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class ConfigLoader {

    private static final String tableProperty = "table_name.txt";

    public static List<Node> loadNodes(String configFilePath) throws IOException {
        Properties props = new Properties();
        try (InputStream input = new FileInputStream(configFilePath)) {
            props.load(input);
        }
        List<Node> nodes = new ArrayList<>();
        for (String key : props.stringPropertyNames()) {
            String value = props.getProperty(key);
            String[] parts = value.split(",");
            String address = parts[0];
            Role role = Role.valueOf(parts[1].toUpperCase());
            Node node = new Node(key, address, role);
            nodes.add(node);
        }
        return nodes;
    }

    public static Node getMasterNode(String configFilePath) throws IOException {
        List<Node> nodes = loadNodes(configFilePath);
        return nodes.stream()
                .filter(node -> node.getRole() == Role.MASTER)
                .findFirst()
                .orElseThrow(() -> new RuntimeException("No master node found"));
    }

    public static List<String> readTableNames() {
        List<String> tableNames = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(tableProperty))) {
            String line;
            while ((line = reader.readLine()) != null) {
                tableNames.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return tableNames;
    }

    public static void writeTableNames(List<String> tableNames) {
        try {
            File file = new File(tableProperty);
            if (!file.exists()) {
                file.createNewFile();
                tableNames.add(Const.NAME);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(tableProperty, true))) {
            for (String tableName : tableNames) {
                writer.write(tableName);
                // 换行
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

